package com.joey.protocol;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;

import com.joey.base.util.FileUtil;
import com.joey.base.util.LogUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by Joey on 2018/3/29.
 */

public abstract class DownloadResponseListener extends NetResponseListener {

    private String saveFullPath;
    private final int MES_UPDATE_PROGRESS = 0x001;
    private final int MES_FINISH = 0x002;
    private int count;

    /**
     * @param saveFullPath
     */
    public DownloadResponseListener(String saveFullPath) {
        this.saveFullPath = saveFullPath;
        mainHandler = new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case MES_UPDATE_PROGRESS:
                        count++;
                        removeMessages(MES_UPDATE_PROGRESS);
                        if (msg.getData() == null) {
                            return;
                        }
                        long total = msg.getData().getLong("total");
                        long progress = msg.getData().getLong("progress");
                        LogUtils.e("count = " + count);
                        mainHandler.removeMessages(MES_UPDATE_PROGRESS);
                        onProgress(total, progress, progress * 100.0f / total);
                        break;
                }
            }
        };
    }

    @Override
    public void onSuccess(Call call, Response response) {
        InputStream is = null;
        byte[] buf = new byte[4096];
        int len = 0;
        FileOutputStream fos = null;
        final ResponseError error = new ResponseError();
        // 储存下载文件的目录
        try {
            is = response.body().byteStream();
            final long total = response.body().contentLength();
            final File file = new File(saveFullPath);
            fos = new FileOutputStream(file);
            long sum = 0;
            while ((len = is.read(buf)) != -1) {
                fos.write(buf, 0, len);
                sum += len;
                updateProgress(total, sum);
            }
            fos.flush();
            mainHandler.post(new Runnable() {
                @Override
                public void run() {
                    // 下载完成
                    mainHandler.removeMessages(MES_UPDATE_PROGRESS);
                    onProgress(total, total, 100);
                    onSuccess(file, error);
                }
            });

            return;
        } catch (Exception e) {
            error.setStatus(ResponseError.ERROR_BY_PARSE);
            error.setMessage(e.getMessage());
        } finally {
            try {
                if (is != null)
                    is.close();
            } catch (IOException e) {
                error.setStatus(ResponseError.ERRPR_BY_SERVER);
                error.setMessage(e.getMessage());
            }
            try {
                if (fos != null)
                    fos.close();
            } catch (IOException e) {
                error.setStatus(ResponseError.ERRPR_BY_SERVER);
                error.setMessage(e.getMessage());
            }
        }
        try {
            onError(error);
        } catch (Exception ee) {
            ee.printStackTrace();
        }
    }

    @Override
    public void onError(Call call, ResponseError error) {

    }

    @Override
    final public void onSink(long total, long sink, int index, boolean done) {

    }

    public abstract void onProgress(long total, long progress, float percent);

    public abstract void onSuccess(File file, ResponseError error);


    private void updateProgress(final long total, final long progress) {
        Message msg = mainHandler.obtainMessage(MES_UPDATE_PROGRESS);
        msg.what = MES_UPDATE_PROGRESS;
        Bundle bundle = new Bundle();
        bundle.putLong("total", total);
        bundle.putLong("progress", progress);
        msg.setData(bundle);
//        mainHandler.sendMessage(msg);
        mainHandler.sendMessageDelayed(msg, 50);
    }

    /**
     * 解析文件头
     * Content-Disposition:attachment;filename=FileName.txt
     * Content-Disposition: attachment; filename*="UTF-8''%E6%9B%BF%E6%8D%A2%E5%AE%9E%E9%AA%8C%E6%8A%A5%E5%91%8A.pdf"
     */
    private static String getHeaderFileName(Response response) {
        String dispositionHeader = response.header("Content-Disposition");
        if (!TextUtils.isEmpty(dispositionHeader)) {
            dispositionHeader.replace("attachment;filename=", "");
            dispositionHeader.replace("filename*=utf-8", "");
            String[] strings = dispositionHeader.split("; ");
            if (strings.length > 1) {
                dispositionHeader = strings[1].replace("filename=", "");
                dispositionHeader = dispositionHeader.replace("\"", "");
                return dispositionHeader;
            }
            return "";
        }
        return "";
    }
}
